package com.tcrow.aop;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

import com.jfinal.core.Controller;
import com.tcrow.utils.DateUtils;
import org.apache.log4j.Logger;

import java.util.Date;
import java.util.Enumeration;

/**
 * 作者 tcrow 创建时间 19/06/2015.
 * 功能描述：
 * 处理全局异常，捕捉所有异常返回给API调用方，防止未知异常的发生，导致无法预测的结果
 * 修改记录：
 */
public class ExcptionAOP implements Interceptor {
    protected final static Logger logger = Logger.getLogger(ExcptionAOP.class);
    @Override
    public void intercept(Invocation inv) {
        Controller controller = (Controller)inv.getController();
        try {
            inv.invoke();
            Enumeration<String> attrNames = controller.getAttrNames();
            logger.info("Return data-------------{"+ DateUtils.formatDateToStyle(null, new Date())+"}-------------------------");
            StringBuffer sb = new StringBuffer();
            sb.append("{");
            while (attrNames.hasMoreElements()){
                String attrName = attrNames.nextElement();
                sb.append(attrName).append(" : ").append(JSON.toJSONString(controller.getAttr(attrName))).append(",");
            }
            logger.info(sb.toString().substring(0,sb.toString().lastIndexOf("")-1)+"}");
            logger.info("-----------------------------------------------------------------------------------------");
        }catch (Exception e){
            logger.error(e);
            e.printStackTrace();
            controller.renderError(-999999);
        }
    }
}
